// src/composables/useSse.ts
import { ref, onUnmounted } from "vue";
import FingerprintJS from "@fingerprintjs/fingerprintjs";
import { useUserStore } from "../../stores/UserStore";

export let eventSource: EventSource | null = null;

// 连接到SSE服务
export const connect = async () => {
  if (!eventSource) {
    const clientKey = await createClientKey();
    const url = `http://localhost:8888/sse/connect/${clientKey}`;
    eventSource = new EventSource(url);

    console.log("Server-Sent Events 连接成功");

    eventSource.onerror = (event) => {
      console.log("Server-Sent Events 连接中断", event);
    };

    eventSource.onopen = (event: Event) => {
      setTimeout(() => {
        console.log("Server-Sent Events 重连成功", event);
      }, 500);
    };
  }
};

// 关闭SSE服务连接
export const close = async () => {
  if (eventSource) {
    console.log("Server-Sent Events 关闭连接");
    eventSource.close();
    eventSource = null;
    // 主动退出情况下，通知后端释放sse资源
    /* if (getToken()) {
        await handleClose(await createClientKey())
    } */
  }
};

// 创建客户端key
const createClientKey = async () => {
  const userStore = useUserStore();
  const browserId = await createBrowserId();
  return `${userStore.userInfo.userId}:${browserId}`;
};

// 处理SSE返回数据，从callback函数中获取
export const handleSseMessage = <T>(callback: MessageCallbackType<T>) => {
  if (eventSource) {
    eventSource.onmessage = (event) => {
      const data = JSON.parse(event.data) as SSEResponseType<T>;
     // console.log("Server-Sent Events 收到消息", data);
      callback(data);
    };
  }
};

// sse 消息callback 函数类型
export type MessageCallbackType<T> = (response: SSEResponseType<T>) => void;

// 处理SSE返回类型
export interface SSEResponseType<T> {
  type: string;
  data: T;
}

// 获取浏览器指纹
export const createBrowserId = async () => {
  const fp = await FingerprintJS.load();
  const resp = await fp.get();
  return resp.visitorId;
};
